package com.lsl.singleton_pattern.ticketmaker;

/**
 * 在下面的TicketMaker类中，每次调用getNextTicketNumber方法都会返回1000,1001,1002...的数列
 * 我们可以用它生成票的编号或者其他序列号。
 * 现在我们要确保该类只能生成1个实例
 *
 * @author Zed
 * @description
 * @date 2022/11/3 21:31
 */
public class TicketMaker implements Runnable {
    private int ticket = 1000;
    private static TicketMaker ticketMaker = null;

    private TicketMaker() {
        System.out.println("生成了一个TicketMaker类");
        slowdown();
    }

    public synchronized static TicketMaker getInstance() {
        if (ticketMaker == null) {
            ticketMaker = new TicketMaker();
        }
        return ticketMaker;
    }

    public synchronized int getNextTicketNumber() throws InterruptedException {
        Thread.sleep(1000);
        return ticketMaker.ticket++;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + ":" + ticketMaker.getNextTicketNumber());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void slowdown() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
